package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.dto.PageResult;
import cn.itcast.hotel.dto.RequestParamsDto;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.index.query.functionscore.ScriptScoreFunctionBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 去es中根据条件查询，获取结果集，并封装
     * @param dto
     * @return
     */
    @Override
    public PageResult search(RequestParamsDto dto) throws IOException {
        //2.创建搜索请求对象，并指定索引名称
        SearchRequest searchRequest=new SearchRequest("hotel");


        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();


        //3.执行搜索条件设置
        if(dto.getKey()==null || dto.getKey().equals("")){
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }else{
           boolQueryBuilder.must(QueryBuilders.matchQuery("all",dto.getKey()));
        }
        //城市
        if(dto.getCity()!=null && !dto.getCity().equals("")){
            boolQueryBuilder.filter(QueryBuilders.termQuery("city",dto.getCity()));
        }
        //品牌
        if(dto.getBrand()!=null && !dto.getBrand().equals("")){
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand",dto.getBrand()));
        }
        //星级
        if(dto.getStarName()!=null && !dto.getStarName().equals("")){
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName",dto.getStarName()));
        }
        //价格区间
        if(dto.getMinPrice()!=null && dto.getMaxPrice()!=null){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(dto.getMinPrice()).lte(dto.getMaxPrice()));
        }

        //相关性算分
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD",true),
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
        );
        searchRequest.source().query(functionScoreQueryBuilder);

        //地址定位排序
        if(dto.getLocation()!=null && !dto.getLocation().equals("")){
            searchRequest.source().sort(
                    SortBuilders.geoDistanceSort("location",new GeoPoint(dto.getLocation()))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS)
            );
        }





        //4.执行分页
            //页码转化条数
            int from=(dto.getPage()-1)*dto.getSize();
        searchRequest.source().from(from).size(dto.getSize());


        //1.搜索
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);


        //7.创建一个集合，用来封装数据
        List<HotelDoc> hotelList=new ArrayList<>();

        //5.数据结果解析封装
        SearchHit[] hits = response.getHits().getHits();
        //5.1 获取总条数
        long total = response.getHits().getTotalHits().value;
        for (SearchHit hit : hits) {
            //获取每一条文档
            String hotelDocStr = hit.getSourceAsString();
            //转化类型
            HotelDoc hotelDoc = JSON.parseObject(hotelDocStr, HotelDoc.class);

            //获取距离
            Object[] sortValues = hit.getSortValues();
            if(sortValues!=null && sortValues.length>0){
                hotelDoc.setDistance(sortValues[0]);
            }


            hotelList.add(hotelDoc);
        }

        //6.封装数据
        PageResult pageResult=new PageResult(total,hotelList);

        return pageResult;
    }
}
